using System;
using System.IO;
using System.Diagnostics;

//http://blogs.msdn.com/rido/articles/FileRollerTraceListener.aspx

namespace RidoCode.LogManager
{	
	public class FileRollerTraceListener : TraceListener
	{

		private TextWriter writer;

		
		public FileRollerTraceListener() : base("TextWriter")
		{
		}

		public FileRollerTraceListener(Stream stream) : this(stream, string.Empty)
		{
		}

		public FileRollerTraceListener(TextWriter writer) : this(writer, string.Empty)
		{
		}

		public FileRollerTraceListener(string fileName) : 
			this(new StreamWriter(
				FileRoller.ResolveOrCreateRollingFile(fileName), true))
		{			
		}

		public FileRollerTraceListener(Stream stream, string name) : base(name)
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			this.writer = new StreamWriter(stream);
		}

		public FileRollerTraceListener(TextWriter writer, string name) : base(name)
		{
			if (writer == null)
			{
				throw new ArgumentNullException("writer");
			}
			this.writer = writer;
		}

		public FileRollerTraceListener(string fileName, string name) : this(new StreamWriter(fileName, true), name)
		{
		}

		public override void Close()
		{
			if (this.writer != null)
			{
				this.writer.Close();
			}
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				this.Close();
			}
		}

		public override void Flush()
		{
			if (this.writer != null)
			{
				this.writer.Flush();
			}
		}

		public override void Write(string message)
		{
			if (this.writer != null)
			{
				if (base.NeedIndent)
				{
					this.WriteIndent();
				}
				this.writer.Write(message);
			}
		}

		public override void WriteLine(string message)
		{
			if (this.writer != null)
			{
				if (base.NeedIndent)
				{
					this.WriteIndent();
				}
				this.writer.WriteLine(message);
				base.NeedIndent = true;
			}
		}

		public TextWriter Writer
		{
			get
			{
				return this.writer;
			}
			set
			{
				this.writer = value;
			}
		}



	}
}
